package com.ksyun.campus.metaserver.services;

import com.alibaba.fastjson.JSONObject;
import com.ksyun.campus.metaserver.config.dataserverconfig.DataServerConfigProperties;
import com.ksyun.campus.metaserver.config.metaserverconfig.MetaServerConfigProperties;
import com.ksyun.campus.metaserver.config.zookperconfig.ZookeeperConfigProperties;
import com.ksyun.campus.metaserver.domain.DataServerInfo;
import com.ksyun.campus.metaserver.domain.ReplicaData;
import lombok.extern.slf4j.Slf4j;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class FsckServices {
    @Autowired
    private ZkClient zkClient;
    @Autowired
    private DataServerConfigProperties dataServerConfigProperties;
    @Autowired
    private MetaServerConfigProperties metaServerConfigProperties;
    @Autowired
    private ZookeeperConfigProperties zookeeperConfigProperties;

    //@Scheduled(cron = "0 0 0 * * ?") // 每天 0 点执行
    @Scheduled(fixedRate = 30*60*1000) // 每隔 30 分钟执行一次
    public void fsckTask() {
        if (!zkClient.exists(metaServerConfigProperties.getRootName()) || !zkClient.exists(dataServerConfigProperties.getRootName())){
            return;
        }
        // todo 全量扫描文件列表

        List<String> dataServerNodes = zkClient.getChildren(dataServerConfigProperties.getRootName());

        for (String node: dataServerNodes) {
            DataServerInfo dataServerInfo = parseObjectFrom(zkClient, node, DataServerInfo.class);
            Map<String, ReplicaData> allReplicaDataMap = dataServerInfo.getAllReplicaDataMap();

        }
        // todo 检查文件副本数量是否正常
        // todo 更新文件副本数：3副本、2副本、单副本

        List<String> dataServerNodeList = zkClient.getChildren(dataServerConfigProperties.getRootName());
        // todo 记录当前检查结果
        // 设置dataserver



    }


    private <T> T parseObjectFrom(ZkClient zkClient, String node,  Class<T> responseType){
        String dataServerInfoJsonStr = (String) zkClient.readData(node);
        try {
            T result = JSONObject.parseObject(dataServerInfoJsonStr, responseType);
            return result;
        }catch (RuntimeException e) {
//            throw new JSONException("can not cast to JSONObject.", e);
            return null;
        }
    }


}
